//
//  ViewController.swift
//  MyWeatherApp
//
//  Created by Shengbing Li (QXU7859) on 2021/2/27.
//  Copyright © 2021 shanghai. All rights reserved.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        title = "天气"
    }

    @IBAction func searchClick(_ sender: UIButton) {
        if self.textField.text!.count == 0 {
            assert(self.textField.text!.count > 0, "The city entered cannot be empty！")
        }
        let cityListVc = CityListViewController()
        if isIncludeChineseIn(string: self.textField.text!) {
            cityListVc.city = QueryType.query(self.textField.text!)
        }else {
            let whitespace = NSCharacterSet.whitespacesAndNewlines
            let str = (self.textField.text! as NSString).trimmingCharacters(in: whitespace)
            let strArry = str.components(separatedBy: ",")
            let doubleArray = strArry.map { (s) in
                return Double(s)
            }
            cityListVc.city = QueryType.lattlongTuple((doubleArray[0] ?? 31.0, doubleArray[1] ?? -121.00))
        }
        
        navigationController?.pushViewController(cityListVc, animated: true)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    
    @IBAction func clickUI(_ sender: UIButton) {
        print("跳转到UI")
    }
    // The best way is to replace it with a regular one！temporary.
    func isIncludeChineseIn(string: String) -> Bool {
        for (_, value) in string.enumerated() {
            if ("\u{4E00}" <= value  && value <= "\u{9FA5}") {
                return true
            }
            if ((value >= "a" && value <= "z") || (value >= "A" && value <= "Z") ) {
               return true
            }
        }
        return false
    }
}

